package com.share.finance.asset.sjd.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.share.common.common.Page;
import com.share.common.common.Result;
import com.share.common.utils.HttpUtil;
import com.share.common.utils.ObjUtil;
import com.share.finance.asset.sjd.mapper.EventInfoMapper;
import com.share.finance.asset.sjd.model.db.EventInfo;
import com.share.finance.asset.sjd.model.db.UserInfo;
import com.share.finance.asset.sjd.model.vo.EventPageReq;
import com.share.finance.asset.sjd.model.vo.EventReq;
import com.share.finance.asset.sjd.service.IEventInfoService;
import com.share.finance.asset.sjd.service.IFieldConfService;
import com.share.finance.asset.sjd.service.IUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-11-29
 */
@Slf4j
@Service
public class EventInfoServiceImpl extends ServiceImpl<EventInfoMapper, EventInfo> implements IEventInfoService {
    @Value("${rootUrl.riskPre}")
    private String riskPreUrl;
    @Resource
    private EventInfoMapper eventInfoMapper;
    @Autowired
    private IFieldConfService fieldConfService;
    @Autowired
    private IUserInfoService userInfoService;

    @Override
    public Page pageList(EventPageReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<EventInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(req.getName())) {
            queryWrapper.like(EventInfo::getName, req.getName());
        }
        if (StringUtils.isNotBlank(req.getPhoneNo())) {
            queryWrapper.like(EventInfo::getPhoneNo, req.getPhoneNo());
        }
        if (StringUtils.isNotBlank(req.getEventType())) {
            queryWrapper.like(EventInfo::getEventType, req.getEventType());
        }
        if (StringUtils.isNotBlank(req.getIdCard())) {
            queryWrapper.like(EventInfo::getIdCard, req.getIdCard());
        }
        if (StringUtils.isNotBlank(req.getRequest())) {
            queryWrapper.like(EventInfo::getRequest, req.getRequest());
        }
        if (StringUtils.isNotBlank(req.getResponse())) {
            queryWrapper.like(EventInfo::getResponse, req.getResponse());
        }
        if (StringUtils.isNotBlank(req.getResultType())) {
            queryWrapper.like(EventInfo::getResultType, req.getResultType());
        }
        if (StringUtils.isNotBlank(req.getProductCode())) {
            queryWrapper.like(EventInfo::getProductCode, req.getProductCode());
        }
        if (StringUtils.isNotBlank(req.getCreditLimit())) {
            queryWrapper.like(EventInfo::getCreditLimit, req.getCreditLimit());
        }
        queryWrapper.orderByDesc(EventInfo::getId);
        List<EventInfo> list = eventInfoMapper.selectList(queryWrapper);
        return new Page<>(list, new PageInfo<>(list).getTotal(), req);
    }

    @Override
    public Result applyCreditLoan(EventReq req, HttpServletRequest request) {
        //获取userId(必须先绑卡,否则userId还是空的)
        String idCard = (String) req.getData().get("idCard");
        UserInfo userInfo = userInfoService.getByIdCard(idCard);
        if (userInfo != null) {
            req.getData().put("userId", userInfo.getUserId());
        }

        EventInfo eventInfo = createEventInfo(req);
        eventInfo.setIp(request.getRemoteAddr());
        String reqStr = JSON.toJSONString(req);
        log.info("请求参数={}", reqStr);
        String url = riskPreUrl + "/apply/creditLoan";
        Result result = null;
        try {
            log.info("请求风控url={},req={}", url, reqStr);
            String reStr = HttpUtil.post(url, reqStr);
            result = JSON.parseObject(reStr, Result.class);
        } catch (Exception e) {
            result.failure(e.getMessage());
            log.error("调用风控前置接口异常url={}", url, e);
        }
        eventInfo.setRequest(reqStr);
        eventInfo.setResponse(result.toString());
        eventInfoMapper.insert(eventInfo);
        return result;
    }

    @Override
    public Integer saveResult(JSONObject req) {
        EventInfo eventInfo = new EventInfo();
        eventInfo.setResultType(req.getString("resultType"));
        eventInfo.setCreditLimit(req.getString("creditLimit"));
        if (ObjUtil.keySizeIgnoreNull(eventInfo) < 1) {
            return 0;
        }

        LambdaQueryWrapper<EventInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EventInfo::getSessionId, req.get("sessionId"));
        queryWrapper.eq(EventInfo::getEventType, req.get("eventType"));
        return eventInfoMapper.update(eventInfo, queryWrapper);
    }


    private EventInfo createEventInfo(EventReq req) {
        //通用参数
        String productCode = req.getProductCode();
        String eventType = req.getEventType();
        long startTime = System.currentTimeMillis();

        //查询默认数据
        String jsonReqStr = JSON.toJSONString(req);
        Map<String, Object> defaultParam = fieldConfService.calcDefultParam(jsonReqStr, productCode, eventType);

        //填充默认字段
        EventInfo record = JSON.parseObject(JSON.toJSONString(defaultParam), EventInfo.class);

        //常规字段
        record.setStartTime(startTime);//开始时间
        record.setSessionId(req.getSessionId());//订单号
        record.setEndTime(System.currentTimeMillis());//结束时间
        record.setCostTime(record.getEndTime() - record.getStartTime());//耗时
        record.setCreateTime(new Date());//创建事件
        record.setRequest(JSON.toJSONString(req));
        record.setProductCode(productCode);
        record.setEventType(eventType);

        return record;
    }
}
